<?php


namespace App\Http\Controllers\Admin\Activity;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;

//引用http请求类

//引用http请求类

class SugarActivityController extends BaseController
{
    /**
     * @api {post} /sugar/activity/ 抢糖果活动配置新增
     * @apiVersion 0.1.0
     * @apiName 抢糖果活动配置新增
     * @apiGroup 抢糖果活动
     *
     * @apiParam {number} is_open                       是否开启 0否 1是
     * @apiParam {string} activity_name                 活动名称
     * @apiParam {json}   activity_gift_prize           活动商品信息设置 例:[{"id":1,"consume_sugar_num":100,"consume_point_num":100,"purchase_limitation_number":10}] id:礼物id consume_sugar_num:消耗糖果数 consume_point_num:消耗点数 purchase_limitation_number:限制兑换次数
     * @apiParam {string} point_name                    点数名称
     * @apiParam {number} first_sugar_num               第一场糖果活动点数
     * @apiParam {number} second_sugar_num              第二场糖果活动点数
     * @apiParam {number} third_sugar_num               第三场糖果活动点数
     * @apiParam {string} start_time                    开始时间
     * @apiParam {string} end_time                      结束时间
     *
     * @apiSuccessExample 成功响应
     *
     * {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function addSugar(Request $request)
    {
        $haveConfig = $this->getOpenConfig();
        if (!empty($haveConfig)) {
            throw new BasicException(10001, "已有一个正在开启的活动！");
        }
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'is_open'       => 'filled|in:0,1',
                'activity_name' => 'filled|string',
            ],
            []);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $params = $request->only(['is_open', 'activity_name', 'activity_gift_prize', 'consume_sugar_num', 'consume_point_num', 'purchase_limitation_number', 'point_name', 'first_sugar_num', 'second_sugar_num', 'third_sugar_num', 'start_time', 'end_time']);

        $data = $params;
//        $data['start_time'] = strtotime($data['start_time']);
//        $data['end_time'] = strtotime($data['end_time']);
        $data['create_time'] = date('Y-m-d H:i:s');
        $rows = app('model_sugar_activity')->create($data);
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }
        // 删除redis信息
        $this->delRedisInfo();

        return Response::sendData(true);
    }

    /**
     * @api {get} /sugar/activity/ 抢糖果活动配置列表
     * @apiVersion 0.1.0
     * @apiName 抢糖果活动配置列表
     * @apiGroup 抢糖果活动
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     * @apiSuccessExample 成功响应
     *
     *
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 3,
     * "is_open (是否开启 0否 1是)": 1,
     * "activity_name (活动名称)": "起点测试",
     * "activity_gift_prize (活动商品信息配置)": "[{\"id\":1,\"consume_sugar_num\":100,\"consume_point_num\":100,\"purchase_limitation_number\":10}]",
     * "consume_sugar_num": 0,
     * "consume_point_num": 0,
     * "purchase_limitation_number": 0,
     * "point_name (点名称)": "秋意值",
     * "first_sugar_num (第一场糖果活动获取的值)": 10,
     * "second_sugar_num (第二场糖果活动获取的值)": 20,
     * "third_sugar_num (第三场糖果活动获取的值)": 30,
     * "start_time (开始时间)": 1631462400,
     * "end_time (结束时间)": 1631894400,
     * "create_time": "2021-09-13 17:09:46",
     * "update_time": null
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     *
     *
     */
    public function list(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $params = $request->input();

        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $list = app('model_sugar_activity')->where($whereArr)->where($whereFunc)->orderBy('id', 'desc')->paginate($perPage, ['*'], '', $page);

        return Response::sendList($list);
    }

    /**
     * @api {post} /sugar/activity/update 抢糖果活动配置修改
     * @apiVersion 0.1.0
     * @apiName 抢糖果活动配置修改
     * @apiGroup 抢糖果活动
     *
     * @apiParam {number} is_open                       是否开启 0否 1是
     * @apiParam {string} activity_name                 活动名称
     * @apiParam {json}   activity_gift_prize           活动商品信息设置 例:[{"id":1,"consume_sugar_num":100,"consume_point_num":100,"purchase_limitation_number":10}] id:礼物id consume_sugar_num:消耗糖果数 consume_point_num:消耗点数 purchase_limitation_number:限制兑换次数
     * @apiParam {string} point_name                    点数名称
     * @apiParam {number} first_sugar_num               第一场糖果活动点数
     * @apiParam {number} second_sugar_num              第二场糖果活动点数
     * @apiParam {number} third_sugar_num               第三场糖果活动点数
     * @apiParam {string} start_time                    开始时间
     * @apiParam {string} end_time                      结束时间
     * @apiParam {number} id                            主键id
     *
     * @apiSuccessExample 成功响应
     *
     * {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'is_open'       => 'required|in:0,1',
                'activity_name' => 'required|string',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->only(['is_open', 'activity_name', 'activity_gift_prize', 'consume_sugar_num', 'consume_point_num', 'purchase_limitation_number', 'point_name', 'first_sugar_num', 'second_sugar_num', 'third_sugar_num', 'start_time', 'end_time']);
        $id = $request->input('id');

        $haveConfig = $this->getOpenConfig();
        if (!empty($haveConfig) && $id != $haveConfig->id) {
            throw new BasicException(10001, "已有一个正在开启的活动！");
        }
        $data = $params;
//        $data['start_time'] = strtotime($data['start_time']);
//        $data['end_time'] = strtotime($data['end_time']);
        $data['update_time'] = date('Y-m-d H:i:s');

        $rows = app('model_sugar_activity')->where(['id' => $id])->update($data);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }
        $this->delRedisInfo();

        return Response::sendData(true);
    }

    /**
     * @api {delete} /sugar/activity/ 抢糖果活动配置删除
     * @apiVersion 0.1.0
     * @apiName 抢糖果活动配置删除
     * @apiGroup 抢糖果活动
     *
     * @apiParam {number} id                       主键id
     *
     * @apiSuccessExample 成功响应
     *
     * {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');
        $res = app('model_sugar_activity')->where(["id" => $id])->delete();
        $this->delRedisInfo();

        if ($res) return Response::sendData($res);
        throw new BasicException(93044);
    }

    // 获取配置信息
    protected function getOpenConfig()
    {
        return app('model_sugar_activity')->where(["is_open" => 1])->first();
    }

    protected function delRedisInfo()
    {
        $redis = app('redis');
        $redis_key = 'act:sugar_activity:config';
        $redis->del($redis_key);
        $redis_gift_key = 'act:sugar_activity:gift';
        $redis->del($redis_gift_key);
    }

    /**
     * @api {get} /sugar/activity/get_exchange_log 抢糖果活动兑换记录
     * @apiVersion 0.1.0
     * @apiName 抢糖果活动兑换记录
     * @apiGroup 抢糖果活动
     *
     * @apiParam {number} id                       主键id
     *
     * @apiSuccessExample 成功响应
     *
     * {
     * "code": 200,
     * "data": [
     * {
     * "id (主键id)": 1,
     * "activity_id (活动id)": 4,
     * "user_id (用户id)": 643429,
     * "consume_sugar_num (消耗糖果数)": 10,
     * "consume_point_num (消耗积分数)": 10,
     * "gift_id (礼物id)": 1,
     * "create_time (领取时间)": "2021-09-14 17:35:32",
     * "update_time": "2021-09-15 09:43:35",
     * "gift_info (礼物信息)": {
     * "id (礼物id)": 1,
     * "name (礼物名称)": "婚纱少女"
     * },
     * "user_data (用户信息)": {
     * "user_id (用户id)": 643429,
     * "nickname (用户昵称)": "皮卡皮卡皮卡皮卡皮卡"
     * }
     * }
     * ]
     * }
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function get_exchange_log(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $params = $request->input();

        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];
        //$id = $request->input('id');
        $logList = app('model_sugar_activity_log')
            ->with([
                'gift_info' => function ($query) {
                    $query->select('id', 'name');
                },
            ])
            ->with([
                'user_data' => function ($query) {
                    $query->select('user_id', 'nickname');
                },
            ])
            //->where(["activity_id" => $id])
            ->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], '', $page);
        return Response::sendData($logList);
    }
}